<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>视频管理</el-breadcrumb-item>
      <el-breadcrumb-item>视频列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" icon="el-icon-search" @click="searchDialogVisible = true">搜索</el-button>
        </el-col>

        <el-col :span="4" id="saveStyle">
          <el-button type="warning" @click="addDialogVisible = true">添加视频</el-button>
        </el-col>
      </el-row>

      <el-table :data="videosList" style="width: 100%" border stripe>
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="视频描述: ">
                <span>{{ props.row.remark }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="视频名称" prop="videoName"></el-table-column>
        <el-table-column label="视频类型">
          <template slot-scope="scope">
            <span v-text="getTypeName(scope.row.typeId)"></span>
          </template>
        </el-table-column>
        <el-table-column label="点赞数" prop="star" sortable></el-table-column>
        <el-table-column label="状态" prop="status"></el-table-column>
        <el-table-column label="图片" prop="imageId">
          <template slot-scope="scope">
            <el-image style="width: 100px; height: 100px" :src="scope.row.imageId"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="上架时间" prop="createTime" sortable></el-table-column>
        <el-table-column label="操作" width="190px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showUpdateVideo(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeVideoById(scope.row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageIndex"
        :page-sizes="[1, 2, 3]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <el-dialog
      title="搜索"
      :visible.sync="searchDialogVisible"
      width="32%"
      @close="searchDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="queryInfo.query"
        :rules="searchFormRules"
        ref="searchFormRef"
        label-width="100px"
      >
        <el-form-item label="视频名称" prop="keyWord">
          <el-input v-model="queryInfo.query.keyWord" style="width:222px"></el-input>
        </el-form-item>
        <el-form-item label="视频类型" prop="typeId">
          <el-select v-model="queryInfo.query.typeId[0]" placeholder="请选择视频类型">
            <el-option
              v-for="item in videoTypes"
              :key="item.id"
              :label="item.naviName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上架时间" required prop="times">
          <el-date-picker
            v-model="queryInfo.query.times"
            type="daterange"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="searchDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="getVideos()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 新增视频模板 -->
    <el-dialog title="新增视频" :visible.sync="addDialogVisible" width="38%" @close="addDialogClosed">
      <el-alert title="请开始你的操作" type="info" center show-icon :closable="false"></el-alert>

      <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="文件上传"></el-step>
        <el-step title="描述信息"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
        label-position="top"
      >
        <el-tabs v-model="activeIndex" :tab-position="'left'" :before-leave="beforeTabLeave">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="视频名称" prop="videoName">
              <el-input v-model="addForm.videoName" style="width:51%"></el-input>
            </el-form-item>
            <el-form-item label="视频类型" prop="typeId">
              <el-select v-model="addForm.typeId" placeholder="请选择视频类型">
                <el-option
                  v-for="item in videoTypes"
                  :key="item.id"
                  :label="item.naviName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="视频状态" prop="status">
              <el-select v-model="addForm.status" placeholder="请选择视频状态">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="文件上传" name="1">
            <el-form-item label="上传图片" prop="imageId">
              <el-upload
                action="http://api.coco.com/api/upload/image"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                list-type="picture"
                :on-error="handleError"
                :on-success="handleSuccess"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </el-form-item>
            <el-form-item label="上传视频" prop="videoUrl">
              <el-upload
                class="upload-demo"
                drag
                action="http://api.coco.com/api/upload/video"
                :on-success="handleSuccess1"
                :on-error="handleError1"
                :on-remove="handleRemove1"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将文件拖到此处，或
                  <em>点击上传</em>
                </div>
                <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="描述信息" name="2">
            <el-form-item label="上传视频" prop="remark">
              <el-input type="textarea" v-model="addForm.remark" :rows="6"></el-input>
              <el-button type="warning" @click="addVideo()">完成</el-button>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-dialog>

    <!-- 修改视频模板 -->
    <el-dialog title="修改视频" :visible.sync="editDialogVisible" width="38%" @close="editDialogClosed">
      <el-alert title="请开始你的操作" type="info" center show-icon :closable="false"></el-alert>

      <el-steps :space="200" :active="activeIndex1 - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="文件上传"></el-step>
        <el-step title="描述信息"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
        label-position="top"
      >
        <el-tabs v-model="activeIndex1" :tab-position="'left'" :before-leave="beforeTabLeave1">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="视频名称" prop="videoName">
              <el-input v-model="editForm.videoName" style="width:51%"></el-input>
            </el-form-item>
            <el-form-item label="视频类型" prop="typeId">
              <el-select v-model="editForm.typeId" placeholder="请选择视频类型">
                <el-option
                  v-for="item in videoTypes"
                  :key="item.id"
                  :label="item.naviName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="视频状态" prop="status">
              <el-select v-model="editForm.status" placeholder="请选择视频状态">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="文件上传" name="1">
            <el-form-item label="上传图片" prop="imageId">
              <el-upload
                action="http://api.coco.com/api/upload/image"
                :on-preview="handlePreview"
                :on-remove="handleRemove2"
                list-type="picture"
                :on-error="handleError"
                :on-success="handleSuccess2"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传图片文件，且不超过500kb</div>
              </el-upload>
            </el-form-item>
            <el-form-item label="上传视频" prop="videoUrl">
              <el-upload
                class="upload-demo"
                drag
                action="http://api.coco.com/api/upload/video"
                :on-success="handleSuccess3"
                :on-error="handleError1"
                :on-remove="handleRemove3"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将文件拖到此处，或
                  <em>点击上传</em>
                </div>
                <div class="el-upload__tip" slot="tip">只能上传视频文件，且不超过200mb</div>
              </el-upload>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="描述信息" name="2">
            <el-form-item label="上传视频" prop="remark">
              <el-input type="textarea" v-model="editForm.remark" :rows="6"></el-input>
              <el-button type="warning" @click="editVideo()">修改</el-button>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-dialog>

    <!-- 图片预览窗口 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="30%">
      <img :src="previewPath" alt="" class="previewImg">
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      options: [
        {
          value: "上架",
          label: "上架"
        },
        {
          value: "下架",
          label: "下架"
        }
      ],
      queryInfo: {
        query: {
          keyWord: "",
          typeId: [],
          times: []
        },
        pageIndex: 1,
        pageSize: 3
      },
      total: 0,
      videosList: [],
      videoTypes: [],
      searchDialogVisible: false,
      addDialogVisible: false,
      editDialogVisible: false,
      previewVisible: false,
      previewPath: "",
      activeIndex: "0",
      activeIndex1: "0",
      addForm: {},
      editForm: {},
      searchFormRules: {
        keyWord: [
          { min: 2, max: 5, message: "长度在2到5个字符之间", trigger: "blur" }
        ]
      },
      addFormRules: {
        videoName: [
          { required: true, message: "请输入视频名称", trigger: "blur" },
          { min: 2, max: 5, message: "长度在2到5个字符之间", trigger: "blur" }
        ]
      },
      editFormRules: {}
    };
  },
  created() {
    this.getNavis();
    this.getVideos();
  },
  methods: {
    searchDialogClosed() {
      this.$refs.searchFormRef.resetFields();
    },
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
      this.activeIndex = "0"
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
      this.activeIndex1 = "0"
    },
    async getNavis() {
      const res = await this.$http.get("navi/getNavis");
      if (res.status !== 200) {
        return this.$message.error("获取类型列表失败!");
      }
      console.log(res.data);
      this.videoTypes = res.data;
    },
    async getVideos() {
      const res = await this.$http.post(
        "video/getVideosByCondition",
        this.queryInfo
      );
      if (res.status !== 200) {
        return this.$message.error("获取类型列表失败!");
      }
      console.log(res.data.data);
      this.videosList = res.data.data;
      this.total = res.data.total
      this.searchDialogVisible = false;
    },
    getTypeName(id) {
      var a = "";
      this.videoTypes.forEach(element => {
        if (element.id === id) {
          a = element.naviName;
        }
      });
      return a;
    },
    async removeVideoById(id) {
      const cont = await this.$confirm("是否删除该类别信息", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).catch(err => err);

      if (cont !== "confirm") {
        return this.$message.info("已取消删除");
      }

      await this.$http
        .delete("video/delete/" + id)
        .then(resp => {
          if (resp.data !== 1) return this.$message.error("删除失败");
          this.$message.success("删除成功");
          this.getVideos();
        })
        .catch(() => {
          this.$message.error("异常！");
        });
    },
    beforeTabLeave(activeName, oldActiveName) {
      console.log(this.addForm.videoName);
      if (oldActiveName === "0" && this.addForm.videoName === undefined) {
        this.$message.error("请填写名称");
        return false;
      }
      
      // if (
      //   oldActiveName === "1" &&
      //   (this.addForm.imageId === undefined ||
      //     this.addForm.videoUrl === undefined)
      // ) {
      //   console.log(oldActiveName);
      //   this.$message.error("请上传文件");
      //   return false;
      // }
    },
    beforeTabLeave1(activeName, oldActiveName) {
      console.log(this.addForm.videoName);
      if (oldActiveName === "0" && this.editForm.videoName === undefined) {
        this.$message.error("请填写名称");
        return false;
      }
    },
    handleRemove2(file) {
      this.editForm.imageId = undefined;
    },
    handleSuccess2(resp) {
      this.editForm.imageId = resp;
    },
    handleRemove3(file) {
      this.editForm.videoUrl = undefined;
    },
    handleSuccess3(resp) {
      this.editForm.videoUrl = resp;
    },
    //新增的文件相关操作
    handlePreview(file) {
      console.log(file.response);
      this.previewPath = file.response
      this.previewVisible = true
    },
    handleRemove(file) {
      this.addForm.imageId = undefined;
    },
    handleSuccess(resp) {
      this.addForm.imageId = resp;
    },
    handleRemove1(file) {
      this.addForm.videoUrl = undefined;
    },
    handleSuccess1(resp) {
      this.addForm.videoUrl = resp;
    },

    handleError() {
      this.$message.error("请上传图片");
    },
    handleError1() {
      this.$message.error("请上传视频");
    },
    addVideo() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;
        await this.$http
          .post("video/save", this.addForm)
          .then(resp => {
            if (resp.status !== 201) return this.$message.error("添加失败");
            this.$message.success("添加成功");
            this.addDialogVisible = false;
            this.getVideos();
          })
          .catch(() => {
            this.$message.error("异常！");
          });
      });
    },
    showUpdateVideo(row){
      this.editForm = row
      this.editDialogVisible = true
    },
    editVideo(){
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return;
        await this.$http
          .post("video/update", this.editForm)
          .then(resp => {
            if (resp.status !== 201) return this.$message.error("更新失败");
            this.$message.success("更新成功");
            this.editDialogVisible = false;
            this.getVideos();
          })
          .catch(() => {
            this.$message.error("异常！");
          });
      });
    },
    //监听pagesize改变的事件
    handleSizeChange(newSize) {
      console.log(newSize);
      this.queryInfo.pageSize = newSize;
      this.getVideos();
    },
    //监听页码值改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage);
      this.queryInfo.pageIndex = newPage;
      this.getVideos();
    },
  }
};
</script>

<style scoped>
#saveStyle {
  float: right;
}
.previewImg{
  width: 100%;
  height: 400px;
}
</style>